package com.fiberhome.ztelauncher.core;

import android.content.Context;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ItemDecoration;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.fiberhome.zte_launcher.R;
import com.fiberhome.ztelauncher.core.navigation.NavigationAdapter;
import com.fiberhome.ztelauncher.core.page.model.BaseType;
import com.fiberhome.ztelauncher.core.shortcut.ShortcutLayout;
import com.fiberhome.ztelauncher.core.page.StaggeredFragment;
import com.fiberhome.ztelauncher.uilib.EnterAnimLayout;
import com.fiberhome.ztelauncher.uilib.SpaceItemDecoration;
import com.fiberhome.ztelauncher.util.BaiYeAnim;
import com.fiberhome.ztelauncher.util.BitmapUitl;
import com.fiberhome.ztelauncher.util.DataUtil;
import com.fiberhome.ztelauncher.util.DisplayUtil;
import com.fiberhome.ztelauncher.xml.bean.FileBean;
import com.fiberhome.ztelauncher.xml.bean.LaunchDataCommon;
import com.fiberhome.ztelauncher.xml.bean.LauncherLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xc on 2018/3/20.
 * 描述：
 */

public class HomeLayout extends LinearLayout implements FocusCarry {
    public final static int BOTTOM = 0;
    public final static int LEFT = 1;
    public final static int TOP = 2;
    public final static int RIGHT = 3;
    public final static int ANIMA_DEAFULT = 0;
    public final static int ANIMA_FADE = 1;
    public final static int ANIMA_WINDOWS_SHADES = 2;
    public final static int ANIMA_PALTE = 3;
    private int direction;
    private ShortcutLayout shortcutLayout;
    private View vbackgroud;
    private LinearLayout llContent;
    private RecyclerView navView;
    private List<StaggeredFragment> fragmentList = new ArrayList<StaggeredFragment>();
    private int width;
    private int height;
    private NavigationAdapter navAdapger;
    private List<LauncherLayout.Page> pageList;
    private List<LaunchDataCommon.Nav> listNavigation = new ArrayList<LaunchDataCommon.Nav>();
    private EnterAnimLayout flContent;
    private FragmentManager mFragmentManager;
    private StaggeredFragment currentFragment;
    private int currentAnim; //当前动画类别
    private int lastIndex; //上一个frament下标
    private int currentIndex; //当前frament下标
    private FragmentTransaction transaction;
    private int position;
    private FocusCarry navFC, shortCutFC, pageFC;
    private FocusCarry currentFC;
    private int pageDirection;
    private LauncherLayout.PageCommon pageCommon;
	private Context context;
	private int navHeight = 60;
	private int navWidth = 180;
    
    public HomeLayout(Context context) {
        super(context);
        initView(context);
    }

    public HomeLayout (Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public HomeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
    	this.context = context;
        View view = LayoutInflater.from(context).inflate(R.layout.home_layout, this, true);
        vbackgroud = (View) view.findViewById(R.id.vbackgroud);
        shortcutLayout = (ShortcutLayout) view.findViewById(R.id.shortcutLayout);
        llContent = (LinearLayout) view.findViewById(R.id.ll_content);
        pageFC = this;
        shortCutFC = shortcutLayout;
    }

    /**
     * 添加导航栏和内容布局
     * 设置导航栏位置 0-default-bottom  1-left  2-top  3-right
     */
    private void addLayout(int direction) {
        this.direction = direction;
        navView = new RecyclerView(context);
        flContent = (EnterAnimLayout) LayoutInflater.from(getContext()).inflate(R.layout.content_layout, null);
        LinearLayout.LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        lp.weight = 1;
        flContent.setLayoutParams(lp);
        
        LinearLayout.LayoutParams rvlp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        if (direction == BOTTOM) {
            rvlp.height = navHeight;
            rvlp.width = getRecylerviewWidth();
            rvlp.gravity = Gravity.CENTER_HORIZONTAL;
            rvlp.setMargins(0, pageCommon.margin.top, 0, pageCommon.margin.bottom);
            navView.setLayoutParams(rvlp);
            navView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
            
            llContent.setOrientation(LinearLayout.VERTICAL);
            llContent.addView(flContent);
            llContent.addView(navView);
        } else if (direction == LEFT) {
        	rvlp.height = navHeight * pageList.size() + pageList.size() * 20;
            rvlp.width = navWidth;
            rvlp.gravity = Gravity.CENTER_VERTICAL;
            rvlp.setMargins(pageCommon.margin.left, 0, pageCommon.margin.right, 0);
            navView.setLayoutParams(rvlp);
            navView.addItemDecoration(new SpaceItemDecoration(10));
            navView.setLayoutManager(new LinearLayoutManager(getContext()));
            
            llContent.setOrientation(LinearLayout.HORIZONTAL);
            llContent.addView(navView);
            llContent.addView(flContent);
        } else if (direction == TOP) {
        	rvlp.height = navHeight;
            rvlp.width = getRecylerviewWidth();
            rvlp.gravity = Gravity.CENTER_HORIZONTAL;
            rvlp.setMargins(0, pageCommon.margin.top, 0, pageCommon.margin.bottom);
            navView.setLayoutParams(rvlp);
            navView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
            
            llContent.setOrientation(LinearLayout.VERTICAL);
            llContent.addView(navView);
            llContent.addView(flContent);
        } else if (direction == RIGHT) {
        	rvlp.height = navHeight * pageList.size() + (pageList.size() - 1) * 20;
        	rvlp.width = navWidth;
            rvlp.gravity = Gravity.CENTER_VERTICAL;
            rvlp.setMargins(pageCommon.margin.left, 0, pageCommon.margin.right, 0);
            navView.setLayoutParams(rvlp);
            navView.addItemDecoration(new SpaceItemDecoration(10));
            navView.setLayoutManager(new LinearLayoutManager(getContext()));
            
            llContent.setOrientation(LinearLayout.HORIZONTAL);
            llContent.addView(flContent);
            llContent.addView(navView);
        }
    }

    /**
     * 首页数据
     */
    public void setHomeData(LaunchDataCommon launchDataCommon, List<LauncherLayout.Page> pageList,
                            List<FileBean> listPageBean, LauncherLayout.PageCommon pageCommon) {
        this.pageCommon = pageCommon;
        this.pageList = pageList;
//        launchDataCommon.navs.position = 1;
        addLayout(launchDataCommon.navs.position);
        setNavigation(launchDataCommon);
        setFragmentData(listPageBean, pageCommon);
        shortcutLayout.setShortcutData(launchDataCommon.shortcuts.shortcuts, pageCommon, launchDataCommon.navs);
    }

    private void setNavigation(LaunchDataCommon launchDataCommon) {
        LaunchDataCommon.Navs navs = launchDataCommon.navs;
        listNavigation = DataUtil.sortNavs(navs.navs, pageList);
        currentAnim = launchDataCommon.navs.pageSwitch;
        width = getWidth();
        height = getHeight();
        navAdapger = new NavigationAdapter(getContext(), navView, navs, navs.position, getRecylerviewWidth(), height);
        navFC = navAdapger;
        navView.setAdapter(navAdapger);

        navAdapger.setOnSwitchPageListener(new NavigationAdapter.OnSwitchPageListener() {
            @Override
            public void switchPage(int position) {
                HomeLayout.this.position = position;
                showFragment(position);
                if (currentAnim == ANIMA_WINDOWS_SHADES) {
                    BaiYeAnim anim = new BaiYeAnim(flContent);
                    anim.startAnimation(1500);
                }
            }
        });
        BitmapUitl.loadBackground(getContext(), navView, navs.backImg);
        currentFC = navFC;

        post(new Runnable() {
            @Override
            public void run() {
                View view = navView.getLayoutManager().findViewByPosition(0);
                if(view != null) {
                	view.requestFocus();
                }
            }
        });
    }

    private void selectPage(int index, int direction) {
        this.pageDirection = direction;
        Log.i("selectPage", "pageIndex = " + index);
        View view = navView.getLayoutManager().findViewByPosition(index);
        if (view != null) {
            view.setSelected(true);
        }
    }

    private void setFragmentData(List<FileBean> listPageBean, LauncherLayout.PageCommon pageCommon) {
        for (int i = 0; i < pageList.size(); i++) {
            for (int j = 0; j < listPageBean.size(); j++) {
                if (pageList.get(i).id.equals(listPageBean.get(j).id)) {
                    fragmentList.add(StaggeredFragment.newInstance(direction,
                            pageList.get(i), listPageBean.get(j), pageCommon));
                }
            }
        }
        mFragmentManager = ((MainActivity) getContext()).getSupportFragmentManager();
        pageDirection = -1;
        showFragment(currentIndex);
    }

    private void showFragment(final int position) {
        lastIndex = currentIndex;
        currentIndex = position;
        StaggeredFragment fragment = fragmentList.get(position);
        if (currentFragment != fragment) {
            transaction = mFragmentManager.beginTransaction();
            switchAnim();
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
            BaseType bt = null;
            if (currentFragment != null) {
                bt = currentFragment.getSelectedBT();
            }

            currentFragment = fragment;
            if (!fragment.isAdded()) {
                transaction.add(R.id.container_layout, fragment).show(fragment).commitAllowingStateLoss();
            } else {
                transaction.show(fragment).commit();
            }
            if (currentFC == this && pageDirection > 0) {
                currentFragment.focusItem(pageDirection, bt);
            }
        }

        setLuncherBackgroud(position);
    }

    /**
     * 设置luncher背景，可切换
     * @param position
     */
    private void setLuncherBackgroud(int position) {
        if (!TextUtils.isEmpty(pageList.get(position).pageBackground)) {
            BitmapUitl.loadBackground(getContext(), vbackgroud, pageList.get(position).pageBackground);
            vbackgroud.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.fade_in_half));
        }
    }

    private void switchAnim() {
        currentAnim = 3;
        switch (currentAnim) {
            case ANIMA_DEAFULT:

                break;
            case ANIMA_FADE:
                transaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
                break;
            case ANIMA_WINDOWS_SHADES:
                //百叶窗动画
                break;
            case ANIMA_PALTE:
                setSlideDirection();
                break;
            default:
                break;
        }
    }

    /**
     * 胶卷拉动动画
     */
    private void setSlideDirection() {
        if (direction == TOP || direction == BOTTOM) {
            if (currentIndex > lastIndex) {
                //往左滑
                transaction.setCustomAnimations(R.anim.translate_in_right, R.anim.translate_out_left);
            } else {
                //往右滑
                transaction.setCustomAnimations(R.anim.translate_in_left, R.anim.translate_out_right);
            }
        } else {
            if (currentIndex > lastIndex) {
                //往上滑
                transaction.setCustomAnimations(R.anim.translate_in_bottom, R.anim.translate_out_top);
            } else {
                //往下滑
                transaction.setCustomAnimations(R.anim.translate_in_top, R.anim.translate_out_bottom);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(currentFC == null){
            return super.onKeyDown(keyCode, event);
        }
        boolean consumed = currentFC.carry(keyCode);
        if (!consumed) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                if (currentFC == navFC) {
                    if ((direction == LEFT && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)
                            || (direction == RIGHT && keyCode == KeyEvent.KEYCODE_DPAD_LEFT)) {
                        currentFC = pageFC;
                        return currentFC.focus(true);
                    }
                } else if (currentFC == pageFC) {
                    if ((direction == LEFT && keyCode == KeyEvent.KEYCODE_DPAD_LEFT)
                            || (direction == RIGHT && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)) {
                        currentFC = navFC;
                        return currentFC.focus(true);
                    }
                }
            }
            if (keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                if (currentFC == navFC) {
                    if ((direction == TOP && keyCode == KeyEvent.KEYCODE_DPAD_DOWN)
                            || (direction == BOTTOM && keyCode == KeyEvent.KEYCODE_DPAD_UP)) {
                        currentFC = pageFC;
                        return currentFC.focus(true);
                    } else if (direction == TOP && keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                        currentFC = shortCutFC;
                        return currentFC.focus(true);
                    }
                } else if (currentFC == pageFC) {
                    if ((direction == TOP && keyCode == KeyEvent.KEYCODE_DPAD_UP)
                            || (direction == BOTTOM && keyCode == KeyEvent.KEYCODE_DPAD_DOWN)) {
                        currentFC = navFC;
                        return currentFC.focus(true);
                    } else if (direction == BOTTOM && keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                        currentFC = shortCutFC;
                        return currentFC.focus(true);
                    }
                } else if (currentFC == shortCutFC) {
                    if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                        if (direction == TOP) {
                            currentFC = navFC;
                            return currentFC.focus(true);
                        } else {
                            currentFC = pageFC;
                            return currentFC.focus(true);
                        }
                    }
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean carry(int direction) {
        if (currentFragment != null) {
            boolean carried = currentFragment.carry(direction);
            if (!carried) {
                if (this.direction == LEFT || this.direction == RIGHT) {
                    if (direction == KeyEvent.KEYCODE_DPAD_UP && currentIndex > 0) {
                        selectPage(currentIndex - 1, direction);
                        return true;
                    } else if (direction == KeyEvent.KEYCODE_DPAD_DOWN && currentIndex < (listNavigation.size() - 1)) {
                        selectPage(currentIndex + 1, direction);
                        return true;
                    }
                } else if (this.direction == TOP || this.direction == BOTTOM) {
                    if (direction == KeyEvent.KEYCODE_DPAD_RIGHT && currentIndex < (listNavigation.size() - 1)) {
                        selectPage(currentIndex + 1, direction);
                        return true;
                    } else if (direction == KeyEvent.KEYCODE_DPAD_LEFT && currentIndex > 0) {
                        selectPage(currentIndex - 1, direction);
                        return true;
                    }
                }
            }
            return carried;
        }
        return false;
    }

    @Override
    public boolean focus(boolean hasFocus) {
        if (currentFragment != null) {
            return currentFragment.focus(hasFocus);
        }
        return true;
    }
    
    private int getRecylerviewWidth() {
    	if(pageList.size() > 6) {
    		return (getWidth() / (pageList.size() + 2)) * pageList.size();
    	}else {
    		return getWidth() / 8 * pageList.size();
    	}
    }

    /**
     * 切换页面
     */
    public void switchPage() {
        selectPage((currentIndex + 1) % navAdapger.getItemCount(), direction);
        navAdapger.focus(true);
    }
}
